package com.tanhua.server.service;


import com.itheima.dubbo.api.UserApi;
import com.tanhua.autoconfig.template.HuanXinTemplate;
import com.tanhua.autoconfig.template.SmsTemplate;
import com.tanhua.commons.utils.Constants;
import com.tanhua.commons.utils.JwtUtils;
import com.tanhua.model.domain.User;
import com.tanhua.model.vo.ErrorResult;
import com.tanhua.server.exception.BusinessException;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.time.Duration;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author Pan Rundong
 * @Date 2023-02-24 19:04
 * @Desc 用户Service实现类
 */
@Service
public class UserService {
    @Autowired
    private SmsTemplate smsTemplate;
    @Autowired
    private RedisTemplate<String, String> redisTemplate;
    @DubboReference(version = "1.0.0")
    private UserApi userApi;
    @Value("${tanhua.salt}")
    private String salt;
    @Autowired
    private HuanXinTemplate huanXinTemplate;
    @Autowired
    private UserFreezeService userFreezeService;

    /**
     * 发送验证码
     * @Author: Pan Rundong
     * @Date: 2023-02-24 19:51
     * @Greet2u:  （O｀ 3′O）~~♡
     * @param phone
     * @return void
     */
    public void sendCode(String phone) {
        //校验用户状态--------------------------
        User user = userApi.findPhone(phone);
        if (user != null) {
            userFreezeService.checkUserStatus(1,user.getId());
        }
        //1.生成验证码
        String code = "123456";
        //2.发送验证码
//        smsTemplate.sendSms(phone, code);
        //3.存Redis
        redisTemplate.opsForValue().set("CHECK_CODE_" + phone, code, Duration.ofMinutes(5));
    }

    /**
     * 验证码验证
     * @Author: Pan Rundong
     * @Date: 2023-02-24 19:58
     * @Greet2u:  （O｀ 3′O）~~♡
     * @param phone
     * @param verificationCode
     * @return java.util.Map<java.lang.String, java.lang.String>
     */
    public Map<String, Object> verification(String phone, String verificationCode) {
        //1.从redis获得验证码
        String code = redisTemplate.opsForValue().get("CHECK_CODE_" + phone);

        //2.判断是否与用户输入的验证码相同
        if (!verificationCode.equals(code)) {
            //不同，抛出异常
            throw new BusinessException(ErrorResult.loginError());
        }
            //相同，删除redis缓存数据
        redisTemplate.delete("CHECK_CODE_" + phone);

        //3.判断是否为新用户
        boolean isNew = false;
        User user = userApi.findPhone(phone);
        if (user == null) {
            //3.1是，新建用户
            user = new User();
            //设置手机
            user.setMobile(phone);
            //设置默认密码
            String password = "123456";
            password = DigestUtils.md5DigestAsHex((password + salt).getBytes());
            user.setPassword(password);
            //保存，获取用户Id
            Long userId = userApi.save(user);
            user.setId(userId);
            isNew = true;

            //注册环信用户
            String hxUser = "hx"+user.getId();
            Boolean create = huanXinTemplate.createUser(hxUser, Constants.INIT_PASSWORD);
            if(create) {
                user.setHxUser(hxUser);
                user.setHxPassword(Constants.INIT_PASSWORD);
                userApi.update(user);
            }
        }

        //4.生成token
        Map<String, Object> map = new HashMap<>(2);
        map.put("phone", phone);
        map.put("id", user.getId());
        String token = JwtUtils.getToken(map);

        //5.返回
        Map<String, Object> result = new HashMap<>();
        result.put("token", token);
        result.put("isNew", isNew);
        return result;
    }

}
